﻿using System;
using System.Windows.Forms;
using System.Reflection;
using Kobets.Automation.Chimera.AgentConfig.Properties;

namespace Kobets.Automation.Chimera.AgentConfig
{
    public class CustomApplicationContext : ApplicationContext
    {
        private System.ComponentModel.IContainer components;
        private NotifyIcon _notifyIcon;
        private static readonly ConfigForm ConfigForm = new ConfigForm();

        public CustomApplicationContext()
        {
            InitializeContext();
        }

        private static void ContextMenuStripOpening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = false;
        }

        private void NotifyIconMouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            var mi = typeof(NotifyIcon).GetMethod("ShowContextMenu", BindingFlags.Instance | BindingFlags.NonPublic);
            mi.Invoke(_notifyIcon, null);
        }

        private void InitializeContext()
        {
            components = new System.ComponentModel.Container();

            _notifyIcon = new NotifyIcon(components)
            {
                ContextMenuStrip = new ContextMenuStrip(),
                Icon = MyResources.TrayIcon,
                Text = MyResources.CustomApplicationContext_InitializeContext_Chimera_Agent,
                Visible = true
            };

            var openTsmi = new ToolStripMenuItem("Open");
            openTsmi.Click += NotifyIconDoubleClick;
            var exitTsmi = new ToolStripMenuItem("Exit");
            exitTsmi.Click += NotifyIconExitClick;
            _notifyIcon.ContextMenuStrip.Items.Add(openTsmi);
            _notifyIcon.ContextMenuStrip.Items.Add(exitTsmi);
            _notifyIcon.ContextMenuStrip.Opening += ContextMenuStripOpening;
            _notifyIcon.DoubleClick += NotifyIconDoubleClick;
            _notifyIcon.MouseUp += NotifyIconMouseUp;
        }

        private static void NotifyIconExitClick(object sender, EventArgs e)
        {
            ConfigForm.Close();
            Application.Exit();
        }

        private static void NotifyIconDoubleClick(object sender, EventArgs eventArgs)
        {
            ConfigForm.ShowDialog();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null) { components.Dispose(); }
        }
    }
}
